<?php
namespace App\Admin\Controller;

use App\Models\Giveout;
use App\Models\Goldcoins;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;
use ModStart\Admin\Concern\HasAdminCRUD;
use ModStart\Core\Input\Response;
use ModStart\Core\Util\QrcodeUtil;
use ModStart\Detail\Detail;
use ModStart\Form\Form;
use ModStart\Grid\Displayer\ItemOperate;
use ModStart\Grid\Grid;
use ModStart\ModStart;
use ModStart\Widget\TextDialogRequest;
use Illuminate\Support\Facades\File;
use ZipArchive;

class GiveoutController extends Controller
{
    use HasAdminCRUD;
    public function grid()
    {
        $grid = Grid::make('giveout');
        $grid->canDelete(false);
        $grid->id('id', 'ID');
        $grid->text('title', '货币名称');
        $grid->image('cover', '正面');
        $grid->image('icon', '反面');
        $grid->text('numbers', '数量');
        $grid->text('amount', '金额');
//        $grid->switch('state', '是否使用');
        $grid->select('types', '货币类型')->options(['0' => '龙币', '1' => '其他']);;
        $grid->display('created_at', '创建时间');
        $grid->hookItemOperateRendering(function (ItemOperate $itemOperate) {
            $item = $itemOperate->item();
            $itemOperate->push(TextDialogRequest::primary('下载打包二维码', modstart_admin_url('giveout/downfile/'.$item['id'])));
//            $itemOperate->push("<a href='giveout/downfile/'".$item['id'].">下载二维码</a>");
//            $itemOperate->prepend("<a id='down' href='giveout/downfile/".$item['id'].">其他操作</a>");
        });
//        $js = <<<JS
//$("#down").on("click","[data-custom-batch-xxx]",function(){
//    console.log("批量操作");
//    // console.log("获取已勾选ID", __grids.get(0).getCheckedIds());
//    // console.log("获取已勾选条目", __grids.get(0).getCheckedItems());
//});
//JS;
//        ModStart::script($js);
        $this->pageTitle('发行货币');
        return $grid;
    }
    public function form()
    {
        $form = Form::make('giveout');
        $form->text('title', '货币名称');
        $form->image('cover', '正面');
        $form->image('icon', '反面');
        $form->text('numbers', '数量');
        $form->text('amount', '金额');
//        $form->switch('state', '是否使用');
        $form->select('types', '货币类型')->options(['0' => '龙币', '1' => '其他']);
        $form->hookSaving(function (Form $form) {
            if ($form->isModeAdd()) {
                // 增加模式
                $data = $form->dataAdding();
                if(substr($data['cover'],0,4) != 'http'){
                    $data['cover'] = getenv("host_url").$data['cover'];
                }
                if(substr($data['icon'],0,4) != 'http'){
                    $data['icon'] = getenv("host_url").$data['icon'];
                }
                // 替换入库数据
                $form->dataAdding($data);
                 } else if ($form->isModeEdit()) {
                // 修改
                $yuan = $form->item();
                $data = $form->dataEditing();
                if($yuan->numbers != $data['numbers']){
                    return Response::generate(-1, '货币数量不能修改!');
                }
                if(substr($data['cover'],0,4) != 'http'){
                    $data['cover'] = getenv("host_url").$data['cover'];
                }
                if(substr($data['icon'],0,4) != 'http'){
                    $data['icon'] = getenv("host_url").$data['icon'];
                }
                // 替换入库数据
                $form->dataEditing($data);
             }
        });

        $form->hookSaved(function (Form $form) {
            $item = $form->item();
            if(substr($item['cover'],0,4) != 'http'){
                $item['cover'] = getenv("host_url").$item['cover'];
            }
            if(substr($item['icon'],0,4) != 'http'){
                $item['icon'] = getenv("host_url").$item['icon'];
            }
            if ($form->isModeAdd()) {
                // 增加模式
                $dt = $this->getSerialNumber($item['numbers']);
                $lit = [];
                if(count($dt) >1000){
                    $chunk_list = array_chunk($dt, 1000);
                    foreach ($chunk_list as  $new_list){
                        foreach($new_list as $v) {
                            $lit["coin_price"] = $item['amount'];
                            $lit["cover"] = $item['cover'];
                            $lit["icon"] = $item['icon'];
                            $lit["sale_state"] = 0;
                            $lit["out_id"] = $item['id'];
                            $lit["serial_number"] = $v['serial'];
                            $lit["record"] = $v['record'];
                            $lit["created_at"] = date("Y-m-d H:i:s", time());
                            $lit["updated_at"] = date("Y-m-d H:i:s", time());
                            DB::table("goldcoins")->insert($lit);
                        }
                    }
                }else{
                    foreach ($dt as $i => $v) {
                        $lit[$i]["coin_price"] = $item['amount'];
                        $lit[$i]["cover"] = $item['cover'];
                        $lit[$i]["icon"] = $item['icon'];
                        $lit[$i]["sale_state"] = 0;
                        $lit[$i]["out_id"] = $item['id'];
                        $lit[$i]["serial_number"] = $v['serial'];
                        $lit[$i]["record"] = $v['record'];
                        $lit[$i]["created_at"] = date("Y-m-d H:i:s",time());
                        $lit[$i]["updated_at"] = date("Y-m-d H:i:s",time());
                    }
                    DB::table("goldcoins")->insert($lit);
                }
            } else if ($form->isModeEdit()) {
                // 修改
                $lit = [];
                $lit["coin_price"] = $item['amount'];
//                $lit["sale_state"] = 0;
                $lit["icon"] = $item['icon'];
                $lit["cover"] = $item['cover'];
                DB::table("goldcoins")->where("out_id",$item['id'])->update($lit);
            }
        });
        return $form;
    }
    public function detail()
    {
        $detail = Detail::make('giveout');
        $detail->id('id', 'ID');
        $detail->display('created_at', '创建时间');
        $detail->text('title', '货币名称');
        $detail->image('cover', '正面');
        $detail->image('icon', '反面');
        $detail->text('numbers', '数量');
        $detail->text('amount', '金额');
//        $detail->switch('state', '是否使用');
        $detail->select('types', '货币类型')->options(['0' => '龙币', '1' => '其他']);;
        return $detail;
    }

    public function downfile($id)
    {
        set_time_limit(0);
        Goldcoins::where(['out_id' => $id])->chunk(1000, function ($res) {
            foreach ($res as $k => $val) {
                self::makeEqCode($val);
            }
        });
//        打包压缩
        $path_uri = public_path("qrcode/images/" . $id . '/');
        chmod($path_uri, 0777);
        $zipFile = public_path("qrcode/images/" . $id . '_zipfile.zip'); // 压缩文件的路径
        if (!file_exists($zipFile)) {
            touch($zipFile);
            chmod($zipFile, 0777);
            $zip = $this->zipFolder($path_uri, $zipFile);
        }else{
            $zip = true;
        }
        if ($zip) {
            $qr_uri = env("host_url")."/qrcode/images/" . $id . '_zipfile.zip';
            $str = "<div style='width: 50%;height:50%;margin:0 auto;margin-top: 100px'>
                   <div style='margin:20px 60px;  margin-top: 50px;  width: 150px;
    height: 40px;background: #3555cc;text-align: center;line-height:40px;border-radius: 2% '><a href='$qr_uri?response-content-type=application/octet-stream' download  style='color:#f0f0f0;text-decoration: none;'>下载二维码</a></div>
                   </div>";
            return $str;
        }
    }


    public static function makeEqCode($result)
    {
//        $result = (new Goldcoins())->where(['id'=>$id])->first();
//        $phase = (new Giveout())->where(['id'=>$result->out_id])->first();
        if (!$result) {
            return false;
        }
        //$url = config("app.host_uri")."/getGoldcoins/getDetail/".$result->id;
        $url = config("app.host_uri") . "/#/qrcode?id=" . $result->id;
        $path_uri = public_path("qrcode/images/" . $result->out_id . '/');
        if (!is_dir($path_uri)) {
            mkdir($path_uri, '0755', true);
        }
        $file_uri = $path_uri . $result->serial_number . '.png';
        if (!file_exists($file_uri)) {
            $qrCode = QrcodeUtil::png($url, 300);
            // 实例化图像处理器
            $image = Image::make($qrCode);
            // 保存图片到服务器
            $image->save($file_uri);
            return true;
        }
        return true;
    }


    public function getSerialNumber($total)
    {
        //查询现在最大的编号
        $res = DB::table("goldcoins")->orderBy("record","desc")->first();
        $data = [];
        if ($res) {
            $start = $res->record + 1;
            $end = $start + $total;
            for ($i = $start; $i <= $end; $i++) {
                $data[$i]["serial"] = self::setSerial($i);
                $data[$i]["record"] = $i;
            }
        } else {
            for ($i = 1; $i <= $total; $i++) {
//                if($i==0){
//                    $data[$i]["serial"] = "00000";
//                    $data[$i]["record"] = $i;
//                    continue;
//                }
                $data[$i]["serial"] = self::setSerial($i);
                $data[$i]["record"] = $i;
            }
        }
        return $data;
    }


    public static function setSerial($num)
    {
        if($num > 0 &&  $num <= 9 ){
           return  str_pad($num, 5, 0, STR_PAD_LEFT);
        }elseif ($num > 9 &&  $num <= 99){
            return  str_pad($num, 5, 0, STR_PAD_LEFT);
        }elseif ($num > 99 &&  $num <= 999){
            return  str_pad($num, 5, 0, STR_PAD_LEFT);
        }elseif ($num > 999 &&  $num <= 9999){
            return  str_pad($num, 5, 0, STR_PAD_LEFT);
        }elseif ($num > 9999 &&  $num <= 99999){
            return  str_pad($num, 5, 0, STR_PAD_LEFT);
        }elseif ($num > 99999 &&  $num <= 999999){
            return  str_pad($num, 6, 0, STR_PAD_LEFT);
        }
    }

    /**
     * @param $folderPath
     * @param $zipPath
     * @return bool
     * 压缩文件
     */
    public function zipFolder($folderPath, $zipPath)
    {
        $zip = new ZipArchive();
        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
            throw new Exception("Cannot open <$zipPath>\n");
        }
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($folderPath));
        foreach ($files as $name => $file) {
            if (!$file->isDir()) {
                $filePath = $file->getRealPath();
                $relativePath = substr($filePath, strlen($folderPath));
                $zip->addFile($filePath, $relativePath);
            }
        }
        $zip->close();
        return true;
    }
    
}